package com.crl.core.animation
{
	import com.crl.core.IDisposable;
	import com.crl.manager.ITickable;
	import com.crl.manager.TickManager;
	
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.utils.Dictionary;
	
	
	/**
	 * 抽像动画播放器; 
	 * @author crl
	 * 
	 */	
	public class AbstractAnimationPlayer extends Sprite implements ITickable , IDisposable
	{
		protected var _animations:Dictionary;	
		
		protected var _currentAnim:Anim;
		
		protected var _currentFrame:int=0;
		protected var _frameTimer:int=0;
		
		protected var _finished:Boolean=false;
		
		private var _tickManager:TickManager;
		public function AbstractAnimationPlayer()
		{
			_animations=new Dictionary();
		}
		
		public function set tickManager(value:TickManager):void{
			_tickManager=value;
		}
		
		public function addAnimation(name:String, frames:Array, frameRate:Number=0, looped:Boolean=true):void
		{
			var anim:Anim=new Anim(name,frames,frameRate,looped);
			_animations[name]=anim;
			if(_currentAnim==null){
				_currentAnim=anim;
			}
		}
		
		
		public function play():void{
			if(_currentAnim.delay <= 0){
				finished = true;
			}else{
				finished = false;
			}
			render(_currentAnim.frames[_currentFrame]);
		}
		
		/**
		 * 跳转到某一帧 
		 * @param frame
		 * 
		 */		
		public function gotoAndStop(frame:int,scene:String=null):void{
			if(scene != null){
				var anim:Anim=_animations[scene];
				if(anim==null)return;
				_currentAnim=anim;
			}
			
			_currentFrame=frame;
			
			finished=true;
			render(_currentAnim.frames[_currentFrame]);
		}
		public function gotoAndPlay(frame:int,scene:String=null):void{
			if(scene != null){
				var anim:Anim=_animations[scene];
				if(anim==null)return;
				_currentAnim=anim;
			}
			
			_currentFrame=frame;
			play();
		}
		
		public function get currentFrame():int{
			return _currentFrame;
		}
		
		public function get totalFrames():int{
			return _currentAnim.frames.length;
		}
		
		public function dispose():void{
			finished=true;
			_animations=null;
			_currentAnim=null;
		}
		
		public function set finished(bool:Boolean):void{
			_finished=bool;
			if(bool==false){
				_tickManager.add(this);
			}else{
				_tickManager.remove(this);
			}
		}
		
		public function tick(time:int):void{
			_frameTimer+=time;
			if(_frameTimer<_currentAnim.delay){
				return;
			}
			
			_frameTimer-=_currentAnim.delay;
			
			if(_currentFrame == _currentAnim.frames.length-1)
			{
				if(_currentAnim.looped){
					_currentFrame = 0;
				}else{
					finished = true;
				}
			}else{
				_currentFrame++;
			}
			render(_currentAnim.frames[_currentFrame]);
		}
		
		protected function render(frameInfo:*):void{
			//todo;
		}
		
	}
}